<template>
  <div class="p-2">
    <transition>
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="反馈编号" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="请输入编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="问题类型" prop="questionType">
            <el-select v-model="queryParams.questionType" clearable>
              <el-option
                v-for="item in questionTypeList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="提交时间" prop="age">
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleDateRangeChange"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="info"-->
          <!--              plain-->
          <!--              icon="Delete"-->
          <!--              :disabled="multiple"-->
          <!--              v-hasPermi="['system:user:import']"-->
          <!--            >-->
          <!--              导入-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="info"-->
          <!--              plain-->
          <!--              icon="Delete"-->
          <!--              :disabled="multiple"-->
          <!--              v-hasPermi="['system:user:export']"-->
          <!--            >-->
          <!--              导出-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="DeleteFilled"-->
          <!--              @click="handleCleanAll"-->
          <!--              v-hasPermi="['system:user:export']"-->
          <!--            >-->
          <!--              清空-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getFeedbackList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="feedbackList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="反馈编号"
          align="center"
          prop="id"
          v-if="true"
        />
        <el-table-column
          label="用户名"
          align="center"
          prop="userName"
          v-if="true"
        />
        <el-table-column label="联系方式" align="center" prop="contact" />
        <el-table-column label="问题类型" align="center" prop="questionType">
          <template #default="{ row }: { row: ClientOpinionVo }">
            {{ questionTypeMap.get(row.questionType ?? "") ?? "未知" }}
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status">
          <template #default="{ row }: { row: ClientOpinionVo }">
            <el-tag
              :type="FeedbackStyleTypeMap.get(row.status ?? '') ?? 'info'"
            >
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="登记时间" align="center" prop="createTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="View"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getFeedbackList"
      />
    </el-card>

    <!-- 反馈详情弹出框 -->
    <el-dialog
      v-model="dialogStatus.isVisible"
      :title="dialogStatus.title"
      width="60%"
      center
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="currentDialogData" label-width="100px">
        <el-row>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="currentDialogData.userName" :disabled="true" />
          </el-form-item>
          <el-form-item label="联系方式" prop="contact">
            <el-input v-model="currentDialogData.contact" :disabled="true" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="问题类型" prop="questionType">
            <el-input
              :value="
                questionTypeMap.get(currentDialogData.questionType ?? '') ??
                '未知'
              "
              :disabled="true"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="问题描述" prop="questionType">
            <el-input
              v-model="currentDialogData.description"
              type="textarea"
              :rows="10"
              :disabled="true"
              class="w-400px!"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="状态" prop="questionType">
            <el-select v-model="currentDialogData.status" placeholder="请选择">
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="问题图片" prop="imageUrl">
            <el-upload
              v-model:file-list="currentDialogData.fileList"
              :auto-upload="false"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :disabled="true"
            >
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>

      <template #footer>
        <el-button plain size="large" icon="Close" @click="handleCloseDialog">
          关闭
        </el-button>
      </template>
    </el-dialog>

    <!--    <el-dialog v-model="previewDialogVisible" title="预览图片" center>-->
    <!--      <img w-full :src="dialogImageUrl" alt="Preview Image" />-->
    <!--    </el-dialog>-->

    <el-image-viewer
      v-if="previewDialogVisible"
      :url-list="[dialogImageUrl]"
      teleported
      @close="handleClosePreview"
    />
  </div>
</template>

<script setup lang="ts">
import {
  deleteLoginLog as deleteLoginLogApi,
  cleanLoginLog as cleanLoginLogApi,
} from "@/service/api/system/loginLog";
import {
  getFeedbackList as getFeedbackListApi,
  getQuestionTypeList as getQuestionTypeListApi,
  getFeedbackDetail as getFeedbackDetailApi,
} from "@/service/api/system/feedback";
import { checkUser } from "@/service/api/system/user/types";
import { ElButton, ElForm, UploadUserFile } from "element-plus";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import {
  ClientOpinionVo,
  SysDictDataVo,
} from "@/service/api/system/feedback/types.ts";
import {
  FeedbackStatusMap,
  FeedbackStyleTypeMap,
} from "@/maps/system/feedback/feedbackMap.ts";
import { convertTimeRange } from "@/utils/request.ts";

const questionTypeList = ref<SysDictDataVo[]>([]);
const questionTypeMap = new Map<string, string>();

const feedbackList = ref<ClientOpinionVo[]>([]);

const loading = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const showSearch = ref(true);

const previewDialogVisible = ref(false);
const dialogImageUrl = ref("");

// 初始dialog状态
const initDialogStatus = {
  isVisible: false,
  title: "",
};

// 状态
const statusArr = reactive([
  {
    value: "0",
    label: "正在处理",
  },
  {
    value: "1",
    label: "未处理",
  },
  {
    value: "2",
    label: "已处理",
  },
  {
    value: "3",
    label: "其他",
  },
]);

// const operatorTypeArr = reactive([
//   {
//     value: 0,
//     label: "其他",
//   },
//   {
//     value: 1,
//     label: "后台用户",
//   },
//   {
//     value: 2,
//     label: "app端用户",
//   },
// ]);

declare type ClientOpinionVoWithExtra = ClientOpinionVo & {
  fileList?: UploadUserFile[];
};

// 初始角色详情dialogData数据
const initDialogData: ClientOpinionVoWithExtra = {
  fileList: [],
};

// 初始query参数
const initQueryParams = {
  id: "",
  userName: "",
  status: "",
  questionType: "",
  timeRange: "",
  pageNum: 1,
  pageSize: 10,
  orderByColumn: "createTime",
  orderType: "desc",
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
};

// 搜索框数据
const data = reactive({
  queryParams: { ...initQueryParams },
  rules: {
    id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
    email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
  },
  dialogStatus: { ...initDialogStatus },
  currentDialogData: {
    ...initDialogData,
  },
});
const { queryParams, currentDialogData, dialogStatus } = toRefs(data);

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  // console.log(queryParams.value)
  getFeedbackList();
};

/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value.timeRange = "";
  queryParams.value.params = {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  };
  handleQuery();
};

/**
 * 获取问题类型列表
 */
const getQuestionTypeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getQuestionTypeListApi({ dictType: "feedback_type" }),
  );
  if (!err) {
    questionTypeList.value = res?.rows ?? [];
    questionTypeList.value.forEach((item: SysDictDataVo) => {
      questionTypeMap.set(item.value ?? "", item.label);
    });
    return true;
  }
  return false;
};

/**
 * 获取反馈列表
 */
const getFeedbackList = async (): Promise<boolean> => {
  loading.value = true;

  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<ClientOpinionVo>, any>(
    getFeedbackListApi(queryParams.value),
  );

  if (!err) {
    console.log("!!!", res);
    feedbackList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    feedbackList.value.forEach((item: ClientOpinionVo) => {
      item.statusMsg = FeedbackStatusMap.get(item.status ?? "") ?? "未知";
    });

    loading.value = false;
    return true;
  }
  loading.value = false;
  return false;
};

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: checkUser[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 查看详情按钮
 */
const handleDetail = async (row: any) => {
  console.log(row.id);
  const [err, res] = await to<BaseResponse<ClientOpinionVo>, any>(
    getFeedbackDetailApi(row.id),
  );
  if (!err) {
    currentDialogData.value = res?.data ?? initDialogData;
    console.log(data);

    currentDialogData.value.fileList =
      res?.data?.ossList?.map((item) => {
        return { name: item?.fileName ?? "", url: item?.url ?? "" };
      }) ?? [];

    dialogStatus.value.title = "用户反馈详情";
    dialogStatus.value.isVisible = true;
  }
};

/**
 * 查看图片详情
 */
const handlePictureCardPreview = (file: UploadUserFile) => {
  previewDialogVisible.value = true;
  dialogImageUrl.value = file.url ?? "";
};

/**
 * 关闭dialog
 */
const handleCloseDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
};

/**
 * 关闭预览
 */
const handleClosePreview = () => {
  previewDialogVisible.value = false;
};

/**
 * 处理删除按钮操作
 */
const handleDelete = async () => {
  // 询问是否删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("此操作将永久删除该登录日志, 是否继续?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消删除",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(
      deleteLoginLogApi(ids.value),
    );

    if (!err) {
      ElMessage({
        message: "删除登录日志成功",
        type: "success",
      });
      await getFeedbackList();
    }
  }
};

/**
 * 清空所有反馈
 */
const handleCleanAll = async () => {
  // 询问是否删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定清空所有反馈记录？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消清空",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(cleanLoginLogApi());

    if (!err) {
      ElMessage({
        message: "清空反馈记录成功",
        type: "success",
      });
    }
  }
};

onMounted(() => {
  getQuestionTypeList();
  getFeedbackList();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }
}

.dialogFooter {
  margin: 55px 0 0 220px;
}

.innerDialogFooter {
  margin: 55px 0 0 230px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 30px;
  }
}

.innerFooter {
  margin: 20px 0 0 200px;
}

:deep(.el-upload) {
  display: none !important;
}

/*去除upload组件过渡效果*/
:deep(.el-upload-list__item) {
  transition: none !important;
}
</style>
